package com.boot.unity.api.wx.controller;

import com.alibaba.fastjson.JSONObject;
import com.boot.unity.api.utils.IdUtil;
import com.boot.unity.api.utils.images.Base64Utils;
import com.boot.unity.api.wx.config.WxResponseCode;
import com.boot.unity.api.wx.service.CommonUtilUrlService;
import com.boot.unity.api.wx.service.WxStorageService;
import com.boot.unity.api.wx.utils.ResponseUtil;
import org.apache.commons.io.FilenameUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.Resource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.util.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
import java.util.Base64;
import java.util.List;

/**
 * 对象存储服务
 */
@RestController
@RequestMapping("/wx/storage")
@Validated
public class WxStorageController {
    private final Log logger = LogFactory.getLog(WxStorageController.class);

    @Autowired
    private WxStorageService wxStorageService;

    @Autowired
    private CommonUtilUrlService commonUtilUrlService;

    @Value("${img.filePath}")
    private String filePath;

    @Value("${img.wxfilePath}")
    private String wxfilePath;

    @Value("${img.url}")
    private String url;

    @Value("${img.key}")
    private String key;


    @Value("${serv.qzip}")
    private String qzip;

    @PostMapping("/uploadBmImg")
    public Object uploadBmImg(@RequestParam("file") MultipartFile file,@RequestParam("cardNo") String cardNo,@RequestParam("key") String key) throws IOException {
         return wxStorageService.uploadBmImg(file, cardNo,key);
    }


    @PostMapping("/upload")
    public Object upload(@RequestParam("file") MultipartFile file,@RequestParam("key") String key) throws IOException {
        return wxStorageService.upload(file, key);
    }

    @PostMapping("/cardupload")
    public Object cardupload(@RequestParam("file") MultipartFile file,@RequestParam("key") String key) throws IOException,Exception {
        if(StringUtils.isEmpty(key)){
            return ResponseUtil.noAuth();
        }
        if (!WxResponseCode.key.equals(key)) {
            return ResponseUtil.noAuth();
        }
        String originalFilename = file.getOriginalFilename();
        // 得到文件的后缀
        String fileExtension = FilenameUtils.getExtension(originalFilename);
//        originalFilename = originalFilename;
        // 允许上传的后缀集合
        List<String> allowedExtensions = Arrays.asList("jpg","jpeg");
        if (!allowedExtensions.contains(fileExtension.toLowerCase())) {
            return ResponseUtil.fail(500,"上传了不被允许的文件格式,只允许jpg,jpeg格式");
        }
        byte[] fileContent = IOUtils.toByteArray(file.getInputStream());
        String imgCon = Base64.getEncoder().encodeToString(fileContent);
        /*String imgName = IdUtil.uuid()+".jpg";
        Base64Utils.GenerateImageJPG(imgCon,filePath+"wxfile//",imgName);
        System.out.println("请求到了指定路径的图片的base64的数据，并保存成功。");
        //将文件推送到对方的服务器的指定路径下面 yushuaixm
        String qzWxFileUrl = "http://"+qzip+":9002/wx/storage/wx_file_create";
        JSONObject qzParamJson = new JSONObject();
        qzParamJson.put("key",this.key);
        qzParamJson.put("imgStr",imgCon);
        qzParamJson.put("imgName",imgName);
        commonUtilUrlService.post(qzWxFileUrl,qzParamJson.toString());
        System.out.println("请求到了指定路径的图片的base64的数据，发送到了对应的服务器文件。请求地址："+qzWxFileUrl);
        String resulturl = url+"wxfile/"+imgName;*/
        JSONObject rJson = new JSONObject();
//        rJson.put("url",resulturl);
        rJson.put("url",imgCon);
        System.out.println("请求结果：。"+rJson.toString());
        return  rJson;
    }


    @PostMapping("/wx_file_create")
    public Object wx_file_create(@RequestBody JSONObject json){
        // System.out.println("json-WX请求参数："+json.toString());
        String keys = json.getString("key");
        System.out.println(keys);
        System.out.println(key);
        JSONObject result = new JSONObject();
        if(org.apache.commons.lang3.StringUtils.isEmpty(keys)){
            result.put("code","400");
            result.put("msg","密钥不正确，请核实！");
            return result;
        }
        if(!key.equals(keys)){
            result.put("code","400");
            result.put("msg","密钥不正确，请核实！");
            return result;
        }
        String imgStr = json.getString("imgStr");
        String photoName = json.getString("imgName");// IdUtil.uuid()+".jpg";
        System.out.println(photoName);
        System.out.println("路径：：：：："+filePath+"wxfile//");
        Base64Utils.GenerateImageJPG(imgStr,filePath+"wxfile//",photoName);

        result.put("code","200");
        return result;
    }



    @PostMapping("/create")
    public Object create(@RequestBody JSONObject json){
        String keys = json.getString("key");
        JSONObject result = new JSONObject();
        if(org.apache.commons.lang3.StringUtils.isEmpty(keys)){
//            return Result.fail("密钥不正确，请核实！");
            result.put("code","400");
            result.put("msg","密钥不正确，请核实！");
            return result;
        }
        if(!key.equals(keys)){
            result.put("code","400");
            result.put("msg","密钥不正确，请核实！");
            return result;
        }
        String imgStr = json.getString("imgStr");
        String photoName = IdUtil.uuid()+".jpg";
        Base64Utils.GenerateImageJPG(imgStr,filePath,photoName);


        String accUrl = url+photoName;
        result.put("code","200");
        result.put("msg",accUrl);
        return result;
    }



    @PostMapping("/create_jpg")
    public Object create_jpg(@RequestBody JSONObject json){
        String keys = json.getString("key");
        JSONObject result = new JSONObject();
        if(org.apache.commons.lang3.StringUtils.isEmpty(keys)){
//            return Result.fail("密钥不正确，请核实！");
            result.put("code","400");
            result.put("msg","密钥不正确，请核实！");
            return result;
        }
        if(!key.equals(keys)){
            result.put("code","400");
            result.put("msg","密钥不正确，请核实！");
            return result;
        }
        String imgStr = json.getString("imgStr");
        String photoName = json.getString("photoName");//IdUtil.uuid()+".jpg";
        Base64Utils.GenerateImageJPG(imgStr,wxfilePath,photoName);


        String accUrl = url+photoName;
        result.put("code","200");
        result.put("msg",accUrl);
        return result;
    }


    @PostMapping("/create_png")
    public Object create_png(@RequestBody JSONObject json){
        String keys = json.getString("key");
        JSONObject result = new JSONObject();
        if(org.apache.commons.lang3.StringUtils.isEmpty(keys)){
//            return Result.fail("密钥不正确，请核实！");
            result.put("code","400");
            result.put("msg","密钥不正确，请核实！");
            return result;
        }
        if(!key.equals(keys)){
            result.put("code","400");
            result.put("msg","密钥不正确，请核实！");
            return result;
        }
        String imgStr = json.getString("imgStr");
        String photoName = json.getString("photoName");
        Base64Utils.GenerateImagePNG(imgStr,wxfilePath,photoName);


        String accUrl = url+photoName;
        result.put("code","200");
        result.put("msg",accUrl);
        return result;
    }


    @PostMapping("/create_jpg_images")
    public Object create_jpg_images(@RequestBody JSONObject json){
        String keys = json.getString("key");
        JSONObject result = new JSONObject();
        if(org.apache.commons.lang3.StringUtils.isEmpty(keys)){
//            return Result.fail("密钥不正确，请核实！");
            result.put("code","400");
            result.put("msg","密钥不正确，请核实！");
            return result;
        }
        if(!key.equals(keys)){
            result.put("code","400");
            result.put("msg","密钥不正确，请核实！");
            return result;
        }
        String imgStr = json.getString("imgStr");
        String photoName = json.getString("photoName");//IdUtil.uuid()+".jpg";
        Base64Utils.GenerateImageJPG(imgStr,wxfilePath+"images//",photoName);


        String accUrl = url+photoName;
        result.put("code","200");
        result.put("msg",accUrl);
        return result;
    }



}
